package com.zywl.web.controller.sys;

import com.zywl.core.beans.Dictionary;
import com.zywl.core.beans.User;
import com.zywl.service.DictionaryService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.MapUtil;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.web.controller.base.BaseController;
import com.zywl.web.controller.form.DictForm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dict")
public class DictionaryController extends BaseController {
    @Autowired
    private DictionaryService dictionaryService;

    @GetMapping("/dictListPage")
    public ModelAndView dictListPage() {
        ModelAndView mav = new ModelAndView("dict/dictListPage");
        try {
            mav.addObject("dicts", dictionaryService.getTypeList());
        } catch (Exception e) {
            logger.error("获取字典类型列表异常", e);
        }
        return mav;
    }

    @PostMapping("/getDictList")
    public PageResult getDictList(HttpServletRequest request, PageData pageData) {
        PageResult pageResult = null;
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        try {
            Map<String, Object> condition = MapUtil.changeMap(request.getParameterMap());
            pageResult = putToResult(dictionaryService.getPageInfo(condition, pageData));
        } catch (Exception e) {
            logger.error("查询字典列表异常", e);
        }
        return pageResult;
    }

    @GetMapping("/dictSubmitPage")
    public ModelAndView dictAddPage(HttpServletRequest request,String id) {
        ModelAndView mav = new ModelAndView("dict/dictSubmitPage");
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        try {
            if(StringUtils.isNotEmpty(id)){
                Dictionary dictionary = dictionaryService.getById(Long.parseLong(id));
                mav.addObject("dict", dictionary);
                Map<String,Object> map = new HashMap<>();
                map.put("dis_type",dictionary.getDisType());
                map.put("dis_level",Integer.valueOf(dictionary.getDisLevel()) - 1);
                List<Dictionary> dictionaryList = dictionaryService.getListByParams(map);
                mav.addObject("dictLevel", dictionaryList);
            }
            mav.addObject("dics", dictionaryService.getTypeList());
        } catch (Exception e) {
            logger.error("获取字典类型列表异常", e);
        }
        return mav;
    }

    @PostMapping("/dictSubmit")
    public AjaxResult dictSubmit(HttpServletRequest request, DictForm form) {
        AjaxResult ar = new AjaxResult();
        if (form != null) {
            Dictionary dict = new Dictionary();
            String old = null;
            Date date = new Date();
            try {
                if (form.getDisId() != null) {
                    dict = dictionaryService.getById(form.getDisId());
                    old = dict.getDisCodeName();
                    form.setDisCreateTime(dict.getDisCreateTime());
                } else {
                    form.setDisCreateTime(date);
                }
                form.setDisModifyTime(date);
                BeanUtils.copyProperties(form, dict);

                if("1".equals(form.getDisLevel())){
                    dict.setDisParentCode(null);
                }

                if (form.getDisId() == null) {
                    if (isExist(dict.getDisType(), dict.getDisCode())) {
                        ar.error("该字典项已存在，请重新填写");
                        return ar;
                    }
                    dictionaryService.save(dict);
                } else {
                    dictionaryService.update(dict);
                }
            } catch (Exception e) {
                logger.error("提交字典项信息异常", e);
                ar.error("提交字典项信息异常", e);
                return ar;
            }

            ar.setResult(true);
            if (form.getDisId() == null) {
                saveLog(request, LogTypeEnum.DICTIONARY.getKey(), "字典新增-" + dict.getDisCodeName());
                ar.success("新增成功");
            } else if (old != null && !old.equals(form.getDisCodeName())) {
                saveLog(request, LogTypeEnum.DICTIONARY.getKey(), "字典修改-" + old + "→" + form.getDisCodeName());
                ar.success("修改成功");
            } else {
                saveLog(request, LogTypeEnum.DICTIONARY.getKey(), "字典修改-" + form.getDisCodeName());
                ar.success("修改成功");
            }
        } else {
            ar.error("提交失败，参数为空");
            ar.setResult(false);
        }
        return ar;
    }

    @PostMapping("/dictDelete")
    public AjaxResult dictDelete(HttpServletRequest request, String id) {
        AjaxResult ar = new AjaxResult();
        try {
            Dictionary dict = dictionaryService.getById(Long.parseLong(id));
            String codename = Constants.STRING_NULL;
            if (dict != null) {
                codename = dict.getDisCodeName();
            }

            dictionaryService.deleteById(Long.parseLong(id));

            saveLog(request, LogTypeEnum.DICTIONARY.getKey(), "字典删除-" + codename);
            ar.success("删除成功");
        } catch (Exception e) {
            logger.error("删除字典异常", e);
            ar.error("删除字典异常", e);
        }
        return ar;
    }

    @PostMapping("/getMaxByType")
    public int getMaxByType(String type) {
        Integer max = 0;
        try {
            max = dictionaryService.getMaxByType(type);
            max = max == null ? 0 : max;
        } catch (Exception e) {
            logger.error("获取字典类型最大值异常", e);
        }
        return max;
    }


    @PostMapping("/getLevelByType")
    public AjaxResult getLevelByType(String dicttype,String level) {
        AjaxResult ar = new AjaxResult();
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("dis_type",dicttype);
            map.put("dis_level",Integer.valueOf(level) - 1);
            List<Dictionary> dictionaryList = dictionaryService.getListByParams(map);
            ar.success("查询成功",dictionaryList);
        } catch (Exception e) {
            logger.error("获取字典等级数据异常", e);
            ar.error("查询失败");
        }
        return ar;
    }


    private boolean isExist(String type, String code) {
        try {
            if (StringUtils.isNotEmpty(code)) {
                Dictionary dictionary = dictionaryService.getDictionaryByTypeAndCode(type, code);
                if (dictionary != null) {
                    return true;
                }
            } else {
                List<Dictionary> dicts = dictionaryService.getDictionaryByType(type);
                if (dicts != null && !dicts.isEmpty()) {
                    return true;
                }
            }
        } catch (Exception e) {
            logger.error("获取字典项异常", e);
        }
        return false;
    }
}
